package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auther :XJY
 * @date :2022/8/15$ 12:52$
 * @description :  账号登录 过滤器 用于权限校验
 */
@Slf4j
@WebFilter("/*")  //配置过滤器拦截路径   启动类上要加@ServletComponentScan注解
public class LoginCheckFilter implements Filter {

    // org.springframework.util.AntPathMatcher
    // 因为过滤器无法对通配符进行解析 所以用到spring框架中的AntPathMatcher 对拦截路径进行匹配
    //路径匹配器 对路径进行匹配
    private final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("过滤器拦截");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // A. 获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("本次请求的URI为{}", requestURI);
        //设置不被拦截的url
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg",
        };

        // B. 判断本次请求, 是否需要登录, 才可以访问
        boolean matchResult = loginCheck(requestURI, uris);
        // C. 如果不需要，则直接放行
        if (matchResult) {
            log.info("//符合放行路径 放行");
            filterChain.doFilter(request, response);
            return;
        }
        // D.4-1 判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("//已登录 放行");

            // 将登录用户的id存入 threadLocal 对象中
            BaseContext.threadLocal.set((Long) request.getSession().getAttribute("employee"));

            filterChain.doFilter(request, response);
            return;
        }

        // D.4-2 判断 user 登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("//已登录 放行");
            // 将登录用户的id存入 threadLocal 对象中
            BaseContext.threadLocal.set((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }



        // E. 如果未登录, 则返回未登录结果 以流的形式返回结果
        log.info("未登录");
        R<String> error = R.error("NOTLOGIN");
        String jsonString = JSON.toJSONString(error);
        //以流的形式 将结果返回给前端页面
        response.getWriter().write(jsonString);

    }


    /***
     *功能描述 : 对访问路径和放行路径进行匹配 的方法
     * @param requestURI
     * @param uris
     *@return : boolean   若匹配 返回true 否则返回false
     */
    private boolean loginCheck(String requestURI, String[] uris) {

        for (String s : uris) {
            boolean match = PATH_MATCHER.match(s, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
